import os
from datetime import datetime


def rename_file(old_path, new_name):
    # 检查文件是否存在
    if not os.path.exists(old_path):
        print("文件不存在")
        return False

    # 获取文件的目录和扩展名
    directory = os.path.dirname(old_path)
    file_extension = os.path.splitext(old_path)[1]

    # 构造新的文件路径
    new_path = os.path.join(directory, new_name + file_extension)

    # 如果新文件名已存在，添加后缀
    counter = 1
    while os.path.exists(new_path):
        new_path = os.path.join(directory, f"{new_name} ({counter}){file_extension}")
        counter += 1
    # if os.path.exists(new_path):
    #     new_path = os.path.join(directory, new_name + "_" + datetime.now().strftime("%Y%m%d%H%M%S") + file_extension)
    # 重命名文件
    try:
        os.rename(old_path, new_path)
        print(f"文件已重命名为: {new_name + file_extension}")
        return True
    except OSError as e:
        print(f"重命名失败: {e}")
        return False

# # 使用函数
# old_file_path = 'path_to_your_old_file.txt'  # 替换为你的旧文件路径
# new_file_name = 'new_file_name.txt'  # 替换为你想改成的新文件名
#
# # 调用函数
# rename_file(old_file_path, new_file_name)